package saei.persistencia.DAO;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;

import saei.bean.*;
import saei.persistencia.HibernateUtil;

@SuppressWarnings({"rawtypes"})
public class EntidadPersistenteDAO {
    
    protected static SessionFactory sf = null;
    protected static Session session = null;
    static  {
        sf = HibernateUtil.getSessionFactory();
    }

    protected static Session getSession() {
        if(session == null || !session.isOpen()){
            session = sf.openSession();
        }
        
        return session;
    }

    public static void closeSession(){
        if (session.isOpen()) session.close();
    }
    
    public static void persistir(EntidadPersistente ent){
    	Session s = getSession();
		s.beginTransaction();
		if (ent.getId() == null)
			s.save(ent);
		else
			s.update(ent);
		s.getTransaction().commit();
	}
	
	public static EntidadPersistente buscar(EntidadPersistente ent) {
		if (ent.getId() == null)
			return null;
		
		EntidadPersistente entidad = (EntidadPersistente) getSession().get(ent.getClass(), ent.getId());
		return entidad;
	}
	
	public static List buscarPorClase(Class className) {
		return buscarPorClase(className.getSimpleName());
	}
	
	public static List buscarPorClase(String className) {
		List lst = null;
		
		String fromQuery = "from " + className;
		lst = getSession().createQuery(fromQuery).list();
		
		return lst;	
	}
	
	public static List buscarPorClase(Class entityClass, String orderBy) {
		Criteria criteria = getSession().createCriteria(entityClass);
        criteria.addOrder(Order.asc(orderBy));
		
		return criteria.list();	
	}
	
	public static void eliminar(EntidadPersistente ent) throws Exception {
		if (ent.getId() == null)
			return;
		
		Session s = getSession();
		try{
			s.beginTransaction();
			s.delete(ent);
			s.getTransaction().commit();
		}catch (HibernateException e) {
			s.getTransaction().rollback();
			throw new Exception("La entidad se encuentra en uso.");
		}
	}
}
